"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const kurento_client_1 = __importDefault(require("kurento-client"));
const config_1 = require("../config/config");
const events_1 = __importDefault(require("events"));
const { wsUri } = config_1.lConfig.kurentoServer;
class Client extends events_1.default {
    constructor() {
        super();
        this.client = null;
    }
    getClient(callback) {
        if (this.client !== null) {
            return callback(null, this.client);
        }
        (0, kurento_client_1.default)(wsUri, (error, kurentoClient) => {
            if (error) {
                console.log("Could not find media server at address " + wsUri);
                return callback("Could not find media server at address" + wsUri
                    + ". Exiting with error " + error);
            }
            this.client = kurentoClient;
            callback(null, kurentoClient);
        });
    }
    connect(originEndpoint, targetEndpoint) {
        originEndpoint.connect(targetEndpoint, (error) => {
            if (error) {
                return error && error();
            }
        });
    }
    initEndpoint(client, cb) {
        this.createMediaPipeline(client, (pipeline) => {
            this.createEndpoint(pipeline, (endpoint) => {
                if (cb)
                    cb(endpoint, pipeline);
            });
        });
    }
    onIceCandidate(webRtcEndpoint, cb) {
        webRtcEndpoint.on('IceCandidateFound', (event) => {
            var iceCandidate = kurento_client_1.default.getComplexType('IceCandidate')(event.candidate);
            cb(iceCandidate);
        });
    }
    createMediaPipeline(client, cb) {
        client.create('MediaPipeline', (error, pipeline) => {
            if (error) {
                return error && error(error);
            }
            cb && cb(pipeline);
        });
    }
    createEndpoint(pipeline, cb) {
        pipeline.create('WebRtcEndpoint', (error, webRtcEndpoint) => {
            if (error) {
                return error && error(error);
            }
            cb && cb(webRtcEndpoint);
        });
    }
    processOffer(endpoint, sdpOffer, cb) {
        endpoint.processOffer(sdpOffer, (error, sdpAnswer) => {
            if (error) {
                return error && error(error);
            }
            cb && cb(sdpAnswer);
        });
        endpoint.gatherCandidates((error) => {
            if (error) {
                return error && error(error);
            }
        });
    }
    stop() {
    }
}
exports.default = Client;
